#include <myheader.h>
#define PATH_SIZE 100
#define RECV_SIZE 1024
#define SEND_SIZE 1024
/*Usage:  */
int main(int argc, char *argv[])
{
    char *ip = "192.168.112.129";
    char *port = "8080";
    //create the socket_fd
    int socket_fd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socket_fd,-1,"socket");
    struct sockaddr_in sock_addr;
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_addr.s_addr = inet_addr(ip);
    sock_addr.sin_port = htons(atoi(port));
    
    int opt = 1;
    int ret = setsockopt(socket_fd,SOL_SOCKET,SO_REUSEADDR,&opt,
                         sizeof(opt));
    ERROR_CHECK(ret,-1,"setsockopt");
    ret = bind(socket_fd,(struct sockaddr*)&sock_addr,
                   sizeof(sock_addr));
    ERROR_CHECK(ret,-1,"bind");

    //listen 
    ret = listen(socket_fd,10);
    ERROR_CHECK(ret,-1,"listen");

    //accept
    int net_fd = accept(socket_fd,NULL,NULL);
    ERROR_CHECK(net_fd,-1,"accept");

    //recv
    char get_header[RECV_SIZE] = {0};
    memset(get_header,0,sizeof(get_header));

    //get the filepath
    char filepath[PATH_SIZE] = {0};
    memset(filepath,0,sizeof(filepath));
    ret = recv(net_fd,get_header,sizeof(get_header),0);
    ERROR_CHECK(net_fd,-1,"recv");
    char *tail = strstr(get_header," HTTP/1.1");
    char *head = strstr(get_header,"GET /");
    for(int i = 0; i < 5; i++){
        head++;
    }
    for(int i = 0; head != tail; i++, head++){
        filepath[i] = *head;
    }

    //open the file
    int file_fd = open(filepath,O_RDONLY);
    printf("file path:%s\n",filepath);
    if(file_fd < 0){
        char fail[] = "cant find the file!\r\n";
        int send_cnt = send(net_fd,fail,sizeof(fail),0);
        ERROR_CHECK(send_cnt,-1,"fail");
        close(net_fd);
        close(socket_fd);
        return 0;
    }
    ERROR_CHECK(file_fd,-1,"open");
    char send_buf[SEND_SIZE] = {0};
    memset(send_buf,0,sizeof(send_buf));
    int read_cnt = 0;
    while((read_cnt = read(file_fd,send_buf,sizeof(send_buf))) > 0){
        int send_cnt = send(net_fd,send_buf,sizeof(send_buf),0);
        ERROR_CHECK(send_cnt,-1,"send");
        memset(send_buf,0,sizeof(send_buf));
    }
    return 0;    
    
}

